/*
 *  author: lichuang
 *  2010-09-27
 */

#include <assert.h>
#include "queue.h"
#include "common/common.h"
#include "common/array.h"

static queue_node_t* queue_node_create(int value);

static queue_node_t* queue_node_create(int value) {
  queue_node_t *node = (queue_node_t*)malloc(sizeof(queue_node_t));
  assert(node != NULL);
  node->value = value;
  node->next = node->prev = NULL;
  return node;
}

queue_t* queue_create() {
  queue_t *queue = (queue_t*)malloc(sizeof(queue_t));
  assert(queue != NULL);
  queue->head = queue->tail = NULL;
  return queue;
}

void queue_destroy(queue_t *queue) {
  assert(queue != NULL);
  queue_node_t *node, *next;
  for (node = queue->head; node != NULL; node = next) {
    next = node->next;
    free(node);
  }
  free(queue);
}

void queue_print(const queue_t *queue, const char *msg) {
  if (msg != NULL) {
    printf("%s\n", msg);
  } else {
    printf("\n");
  }
  printf("elements of the queue:\n");
  queue_node_t *node = queue->head;
  for (; node != NULL; node = node->next) {
    printf("%d ", node->value);
  }
  printf("\n");
}

void enqueue(struct queue_t *queue, int value) {
  assert(queue != NULL);
  queue_node_t *node = queue_node_create(value);
  queue_node_t *head = queue->head;
  if (head == NULL) {
    queue->head = queue->tail = node;
    node->prev = node->next = NULL;
  } else {
    queue_node_t *tail = queue->tail;
    tail->next = node;
    node->prev = tail;
    queue->tail = node;
  }
}

int  dequeue(struct queue_t *queue) {
  assert(queue != NULL);
  queue_node_t *head = queue->head;
  if (head) {
    queue_node_t *node = head->next;
    int value = head->value;
    free(head);
    queue->head = node;
    return value;
  } else {
    return -1;
  }
}

